package com.lz.sports.vm.config

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.library.base.SingleLiveData
import com.lz.library.extension.resString
import com.lz.sports.LogUtils
import com.lz.sports.R
import com.lz.sports.bean.DeviceInfo
import com.lz.sports.core.ProjectManager
import com.lz.sports.db.DeviceDatabase
import com.lz.sports.utils.ToastUtils
import com.lz.sports.utils.toDeviceInfo
import com.lz.ub.UBCManager
import com.lz.ub.UBCScanCallback
import com.lz.ub.core.UBCScanResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.*

class DeviceEnterViewModel : BaseViewModel<BaseModel>(), UBCScanCallback {

    val projectId = ProjectManager.examProjectId()

    val deviceInfo = MutableLiveData<DeviceInfo>()

    //开始搜索或者停止
    val searchState = MutableLiveData(R.string.device_enter_search.resString())

    var isSearching = MutableLiveData(false)

    //延时操作
    val delayEvent = SingleLiveData<Int>()

    override fun onCreate(owner: LifecycleOwner) {
        UBCManager.get().addUBCScanCallback(this)
        UBCManager.get().restart()
        delayEvent.setValue(2)
    }

    override fun onCleared() {
        super.onCleared()
        UBCManager.get().removeUBCScanCallback(this)
        if (isSearching.value == true) {
            LogUtils.i("stopscan...")
            UBCManager.get().stopScan()
        }
    }

    override fun onScanResult(result: UBCScanResult) {
        if (isSearching.value!!) {
            launch {
                val async = async(Dispatchers.Default) {
                    result.toDeviceInfo(projectId, DeviceDatabase.get().hasDeviceInfo(result.mac, projectId))
                }
                deviceInfo.value = async.await()
            }
        }
    }

    //查询设备
    fun search() {
        if (!isSearching.value!!) {
            isSearching.value = true
            UBCManager.get().scan()
            searchState.value = R.string.device_enter_stop.resString()
        }
    }

    //停止
    fun stopSearch() {
        if (isSearching.value!!) {
            isSearching.value = false
            UBCManager.get().stopScan()
            searchState.value = R.string.device_enter_search.resString()
        }
    }

    //保存
    fun save(deviceInfoList: List<DeviceInfo>) {
        launch {
            flow {
                try {
                    DeviceDatabase.get().addScanDeviceInfoList(deviceInfoList)
                    emit(true)
                } catch (_: Exception) {
                    emit(false)
                }
            }.flowOn(Dispatchers.IO)
                .onStart { updateDialogLoading(true) }
                .onCompletion { updateDialogLoading(false); finish() }
                .collect { ToastUtils.showMyToast(R.string.saveSuccess) }
        }
    }
}